﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;

namespace CommonClass.DataHandler
{
    /// <summary>
    /// 导出的时候List数据转为DataSet类型
    /// </summary>
    public  static  class ListToDataSet
    {
        /// <summary>
        /// 对 List类型转换为DataSet的类型  使用方法 List<T>   modelList.ToDataSet<T>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static DataSet ToDataSet<T>(IList<T> list)
        {
            Type elementType = typeof(T);

            var ds= new DataSet();
            var t= new  DataTable();
            ds.Tables.Add(t);
            elementType.GetProperties().ToList().ForEach(propInfo=>
                t.Columns.Add(propInfo.Name,Nullable.GetUnderlyingType(propInfo.PropertyType)??propInfo.PropertyType));
            foreach (T item in list)
            {
                var row = t.NewRow();
                elementType.GetProperties().ToList().ForEach(propInfo => row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value);
                t.Rows.Add(row);
            }
            return ds;
        }
        /// <summary>
        /// linq结果输出转换为DataSet
        /// 例如                         var c  from z in jcxzRows
        ///                              select new { }
        ///                              DataTable table1 = c.IEnumerableCopyToDataTable();
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="array"></param>
        /// <returns></returns>
        public static DataSet IEnumerableCopyToDataTable<T>(this IEnumerable<T> array)
        {
            //var ret = new DataTable();
            //foreach (PropertyDescriptor dp in TypeDescriptor.GetProperties(typeof(T)))
            //    ret.Columns.Add(dp.Name, dp.PropertyType);

            //foreach (T item in array)
            //{
            //    var Row = ret.NewRow();
            //    foreach (PropertyDescriptor dp in TypeDescriptor.GetProperties(typeof(T)))
            //        Row[dp.Name] = dp.GetValue(item);

            //    ret.Rows.Add(Row);
            //}
            //return ret;

            Type elementType = typeof(T);
            var ds = new DataSet();
            var t = new DataTable();
            ds.Tables.Add(t);
            elementType.GetProperties().ToList().ForEach(propInfo =>
                t.Columns.Add(propInfo.Name, Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType));
            foreach (T item in array)
            {
                var row = t.NewRow();
                elementType.GetProperties().ToList().ForEach(propInfo => row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value);
                t.Rows.Add(row);
            }
            return ds;

        }
    }
}
